﻿using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Corp;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using ManagementApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules;
using Modules.Corp;
using Modules.Device;
using Modules.Manager;
using Modules.Project;
using Modules.System.Security;
using Modules.System.User;
using OfficeOpenXml;
using PmSoft.Entity;
using System.ComponentModel.DataAnnotations;
using System.Reflection.Emit;

namespace ManagementApi.Controllers.ManagerPannel
{
    /// <summary>
    /// 常用业务接口-项目管理员角色
    /// </summary>
    [ApiController]
    [Route("/api/v1/manager/common")]
    [Authorize(Roles = "Manager")]
    public class CommonController : ControllerBase
    {
        private readonly CorpService corpService;
        private readonly ManagerService managerService;
        private readonly ProjectService projectService;
        private readonly ProjectCorpService projectCorpService;
        private readonly CardReaderDeviceService sysDeviceService;
        private readonly ProjectManagerApplicationContext applicationContext;
        private readonly SerialNumberService serialNumberService;
        private readonly SecurityService securityService;
        private readonly ProjectOwnAuthorizer ownAuthorizer;

        /// <summary>
        /// </summary>
        /// <param name="sysDeviceService"></param>
        /// <param name="corpService"></param>
        /// <param name="managerService"></param>
        /// <param name="projectService"></param>
        /// <param name="projectCorpService"></param>
        /// <param name="applicationContext"></param>
        /// <param name="serialNumberService"></param>
        /// <param name="securityService"></param>
        /// <param name="ownAuthorizer"></param>
        public CommonController(CardReaderDeviceService sysDeviceService, CorpService corpService, ManagerService managerService, ProjectService projectService, ProjectCorpService projectCorpService, ProjectManagerApplicationContext applicationContext, SerialNumberService serialNumberService, SecurityService securityService, ProjectOwnAuthorizer ownAuthorizer)
        {
            this.corpService = corpService;
            this.managerService = managerService;
            this.applicationContext = applicationContext;
            this.projectService = projectService;
            this.projectCorpService = projectCorpService;
            this.sysDeviceService = sysDeviceService;
            this.serialNumberService = serialNumberService;
            this.securityService = securityService;
            this.ownAuthorizer = ownAuthorizer;
        }

        /// <summary>
        /// 切换项目
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpPut("projectChanges/{projectId}")]
        public ApiResult ProjectChanges(int projectId)
        {
            if (applicationContext.CurrentUser == null) return ApiResult.Failure("系统异常,请重新登陆");
            ManagerInfo? managerInfo = managerService.GetManagerInfo(applicationContext.CurrentUser.Id);
            if (managerInfo == null)
                return ApiResult.Failure("项目管理员信息不存在");

            #region 验证数据权限

            var projects = applicationContext.GetService<ProjectService>().GetProjectInfosByManagerId(managerInfo.ManagerId);
            if (!projects.Any(s => s.ProjectId == projectId)) throw new OwnAuthorizationFailedException();

            #endregion 验证数据权限

            managerService.UpdateDefaultProjectId(managerInfo, projectId);
            return ApiResult.Success("项目切换成功");
        }

        /// <summary>
        /// 总包企业查询
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("corps_zb")]
        public ApiResult<PageDto<CorpInfoDto>> GetCorpsZb([FromQuery] CorpInfoQuery query, int pageIndex = 1, int pageSize = 20)
        {
            query.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            List<ProjectInfo>? projectInfos = new List<ProjectInfo>();
            if (applicationContext.CurrentUser != null)
            {
                projectInfos = projectService.GetProjectInfosByManagerId(applicationContext.CurrentUser.Id) as List<ProjectInfo>;
            }
            List<int?> CorpIds = new List<int?>();
            if (projectInfos != null && projectInfos.Count() > 0)
            {
                CorpIds.Add(projectInfos.First().LumpContractorCorpId);
            }
            var data = corpService.GetCorpInfos(query, pageIndex, pageSize, CorpIds);
            var pageDto = data.AsPageDto(m => m.AsDto(applicationContext));
            return ApiResult<PageDto<CorpInfoDto>>.Success(pageDto);
        }

        /// <summary>
        /// 总包+分包企业查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("corps_manager")]
        public ApiResult<IEnumerable<CorpInfoDto>> GetManagerCorps()
        {
            var corpInfos = corpService.GetCorpsByProjectId(applicationContext.CurrentProjectInfo.ProjectId);
            var dtos = corpInfos.Select(m => m.AsDto(applicationContext));
            return ApiResult<IEnumerable<CorpInfoDto>>.Success(dtos);
        }

        /// <summary>
        /// 通用Excel文件校验
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UploadExcel(IFormFile file)
        {
            try
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 设置为非商业授权
                using (var package = new ExcelPackage(file.OpenReadStream()))
                {
                    var workbook = package.Workbook;
                    var worksheet = workbook.Worksheets[0]; // 假设读取第一个工作表

                    int rows = worksheet.Dimension.Rows;
                    int columns = worksheet.Dimension.Columns;

                    for (int row = 9; row <= rows; row++) // 第一行通常为标题栏，从第二行开始读取数据
                    {
                        for (int col = 1; col <= columns; col++)
                        {
                            var cellValue = worksheet.Cells[row, col].Value?.ToString(); // 读取单元格的值
                            // 对每个单元格的值进行处理 这里可以根据需要将cellValue存储到数据库或进行其他业务操作
                        }
                    }
                }

                return ApiResult.Success("Excel上传并解析成功");
            }
            catch (Exception ex)
            {
                // 处理异常
                return ApiResult.Failure("Excel上传或解析失败：" + ex.Message);
            }
        }

        #region 身份证阅读器

        /// <summary>
        /// 获取读卡器签名
        /// </summary>
        /// <returns></returns>
        //[HttpGet("getReadCardToken")]
        //public ApiResult<string> GetReadCardToken()
        //{
        //    string readId = Guid.NewGuid().ToString();

        //    #region 查询项目的施工总包

        //    var projectCorp = projectCorpService.GetProjectCorpsByProjectId(applicationContext.CurrentProjectInfo.ProjectId).FirstOrDefault(a => a.Role == 项目参建单位类型.总承包单位);
        //    if (projectCorp == null) return ApiResult<string>.Failure("获取读卡器签名失败：当前登录项目没有总承包单位");
        //    var corp = corpService.GetCorpInfo(projectCorp.CorpId);
        //    if (corp == null) return ApiResult<string>.Failure("获取读卡器签名失败：当前登录项目总承包单位不存在");

        //    #endregion 查询项目的施工总包

        //    string token = ReaderEncrypt.AESEncrypt($"{readId},{corp.Code}", isHex: true);
        //    return ApiResult<string>.Success(token);
        //}

        /// <summary>
        /// 同意接入读卡器
        /// </summary>
        /// <returns></returns>
		[HttpPut("confirmCardReader")]
        public ApiResult ConfirmCardReader()
        {
            #region 查询项目的施工总包

            var corp = corpService.GetCorpInfo(applicationContext.CurrentProjectInfo.LumpContractorCorpId);
            if (corp == null) return ApiResult.Failure("获取读卡器签名失败：当前登录项目总承包单位不存在");

            #endregion 查询项目的施工总包

            var cardReaders = sysDeviceService.GetCardReaderDeviceByCorpCode(corp.Code);
            //筛选非待审核的读卡器，大于0则不允许自动审核
            if (cardReaders.Any(m => m.Status != 设备审核状态.待审核))
                return ApiResult.Failure("企业已接入了至少一个读卡器，接入多个需要联系管理员登记读卡器信息,联系电话：13398001090");

            //获取企业最新创建的一个待审核读卡器
            var cardReader = cardReaders.OrderByDescending(m => m.CreateTime).FirstOrDefault(m => m.Status == 设备审核状态.待审核);
            if (cardReader == null)
                return ApiResult.Failure("未获取到当前企业待登记读卡器信息");
            cardReader.Status = 设备审核状态.已审核;
            cardReader.AuditTime = DateTime.Now;
            cardReader.Description = "企业首个身份证读卡器自动登记";
            sysDeviceService.UpdateSysDevice(cardReader);
            return ApiResult.Success("读卡器接入成功");
        }

        #endregion 身份证阅读器

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="passWord"></param>
        /// <returns></returns>
        [HttpPut("updatePassWord")]
        public ApiResult UpdatePassWord([Required(ErrorMessage = "密码不能为空")] string passWord)
        {
            ManagerInfo? managerInfo = managerService.GetManagerInfo(applicationContext.CurrentUser?.Id ?? 0);
            if (managerInfo == null)
                return ApiResult.Failure("劳资专管员不存在");
            SysSecurity? sysSecurity = securityService.GetSysSecurity(managerInfo.SecurityId);
            if (sysSecurity != null)
            {
                sysSecurity.Password = SecurityPasswordHelper.EncodePassword(passWord, UserPasswordFormat.SM4);
                securityService.Update(sysSecurity);
            }
            return ApiResult.Success("修改成功");
        }
    }
}